package com.szsky.sky.demo;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;

/**
 * 数字社科门户，登录admin的加解密。
 *
 * Base64.encodeToString(AESUtils.encrypt("密码".toByteArray(),"!QAZ2wsx@WSX1qaz".toByteArray()) ,2)
 */
@Slf4j
public class AesUtil {

    private static final String KEY = "NQlrO$8*ziPls@w0";
    private static final String KEY2 = "!QAZ2wsx@WSX1qaz";

    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    public static String aesDecrypt(String encrypt) {
        try {
            return aesDecrypt(encrypt, "NQlrO$8*ziPls@w0");
        } catch (Exception e) {
            log.error("aes解密失败", e);
            return "";
        }
    }

    public static String aesEncrypt(String content) {
        try {
            return aesEncrypt(content, "NQlrO$8*ziPls@w0");
        } catch (Exception e) {
            log.error("aes加密失败", e);
            return "";
        }
    }

    public static String binary(byte[] bytes, int radix) {
        return (new BigInteger(1, bytes)).toString(radix);
    }

    public static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    public static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isEmpty(base64Code) ? null : Base64.decodeBase64(base64Code);
    }

    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(1, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        return cipher.doFinal(content.getBytes("utf-8"));
    }


    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }


    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(2, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }


    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(aesDecrypt("516e3e795855d0a005d547e3aa674e8b0664e60124d618ee2f1b61a2866cc930","NQlrO$8*ziPls@w0"));
    }
}
